package xin.ryven.car.android.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import xin.ryven.car.android.data.Music
import xin.ryven.car.android.databinding.ItemMusicBinding
import xin.ryven.car.android.utils.FontUtils

class DislikedAdapter(
    private val context: Context,
    private val onRemoveClick: (Music) -> Unit
) : ListAdapter<Music, DislikedAdapter.ViewHolder>(DislikedDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemMusicBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    fun updateList(newList: List<Music>) {
        submitList(newList)
    }

    inner class ViewHolder(private val binding: ItemMusicBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(music: Music) {
            binding.apply {
                tvTitle.text = music.name
                tvSinger.text = music.singer
                FontUtils.apply(tvTitle)
                FontUtils.apply(tvSinger)

                // 隐藏下载按钮，显示移除按钮
                btnDownload.visibility = View.GONE
                btnRemove.visibility = View.VISIBLE

                root.setOnClickListener { }
                btnRemove.setOnClickListener {
                    onRemoveClick(music)
                }
            }
        }
    }
}

class DislikedDiffCallback : DiffUtil.ItemCallback<Music>() {
    override fun areItemsTheSame(oldItem: Music, newItem: Music): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Music, newItem: Music): Boolean {
        return oldItem == newItem
    }
}